package com.shortlink.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shortlink.common.exception.ClientException;
import com.shortlink.common.exception.ServiceException;
import com.shortlink.mapper.GroupMapper;
import com.shortlink.mapper.LinkMapper;
import com.shortlink.pojos.dto.req.GroupReqDTO;
import com.shortlink.pojos.dto.req.GroupSortReqDTO;
import com.shortlink.pojos.dto.resp.GroupQueryRespDTO;
import com.shortlink.pojos.entity.GroupDO;
import com.shortlink.pojos.entity.LinkDO;
import com.shortlink.common.properties.LinkProperties;
import com.shortlink.service.IGroupService;
import com.shortlink.service.ILinkService;
import com.shortlink.utils.BeanCopyUtils;
import com.shortlink.utils.RandomGenerator;
import com.shortlink.utils.UserContext;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.shortlink.common.constants.AppHttpCodeEnum.GROUP_GID_GENERATE_FREQUENTLY;

@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements IGroupService {

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RBloomFilter gidBloomFilter;
    @Autowired
    LinkProperties linkProperties;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    LinkMapper linkMapper;
    @Autowired
    ILinkService iLinkService;

    @Override
    public void createGroup(String groupName) {
        createGroup(groupName,UserContext.getUsername());
    }

    public void createGroup(String groupName,String username){
        if(groupName==null||groupName==""){
            groupName="默认分组";
        }

        // 检查该用户是否能够创建分组
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, username)
                .eq(GroupDO::getDelFlag, "0");
        List<GroupDO> groupDOList = groupMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == linkProperties.getMaxNum()) {
            throw new ClientException(String.format("已超出最大分组数：%d", linkProperties.getMaxNum()));
        }

        // 创建分组
        int retryCount = 0;
        int maxRetries = 10;
        String gid = null;
        while (retryCount < maxRetries) {
            // 最多重试10次
            gid = generateGid();
            if (StrUtil.isNotEmpty(gid)) {
                GroupDO groupDO=new GroupDO();
                groupDO.setGid(gid);
                groupDO.setGroupName(groupName);
                groupDO.setUsername(username);
                groupDO.setSortOrder(0);
                groupDO.setDelFlag("0");
                groupMapper.insert(groupDO);
                gidBloomFilter.add(gid);
                break;
            }
            retryCount++;
        }
        if (StrUtil.isEmpty(gid)) {
            throw new ServiceException(GROUP_GID_GENERATE_FREQUENTLY);
        }
    }


    /**
     * 创建唯一gid
     * @return
     */
    private String generateGid() {
        String gid = RandomGenerator.generateRandom();
        if (gidBloomFilter.contains(gid)) {
            return null;
        }
        return gid;
    }

    @Override
    public void updateGroup(GroupReqDTO groupReqDTO) {
        GroupDO groupDO = BeanCopyUtils.copyBean(groupReqDTO, GroupDO.class);
        LambdaUpdateWrapper<GroupDO> updateWrapper =Wrappers.lambdaUpdate(GroupDO.class)
                        .eq(GroupDO::getGid,groupReqDTO.getGid());
        groupMapper.update(groupDO,updateWrapper);
    }

    @Override
    public void sortGroup(List<GroupSortReqDTO> groupSortReqDTOList) {
        for (GroupSortReqDTO groupSortReqDTO : groupSortReqDTOList) {
            LambdaUpdateWrapper<GroupDO> updateWrapper =Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getGid,groupSortReqDTO.getGid());
            GroupDO groupDO = BeanCopyUtils.copyBean(groupSortReqDTO, GroupDO.class);
            groupMapper.update(groupDO,updateWrapper);
        }
    }

    @Override
    public void deleteGroup(String gid) {
        Date now= new Date();
        // 逻辑删除group
        LambdaUpdateWrapper<GroupDO> groupDeleteWrapper=Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getGid,gid)
                .set(GroupDO::getDelFlag,"1")
                .set(GroupDO::getDeleteTime,now);
        groupMapper.update(null, groupDeleteWrapper);
        // 获取该组别链接
        LambdaQueryWrapper<LinkDO> queryWrapper =Wrappers.lambdaQuery(LinkDO.class)
                .eq(LinkDO::getGid,gid);
        List<LinkDO> linkDOList = linkMapper.selectList(queryWrapper);
        // 逻辑删除链接
        for (LinkDO linkDO : linkDOList) {
            iLinkService.deleteLink(linkDO.getShortUri());
        }
    }

    @Override
    public List<GroupQueryRespDTO> queryGroup() {
        String username = UserContext.getUsername();
        LambdaQueryWrapper<GroupDO> wrapper=Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername,username);
        List<GroupDO> groupDOList = groupMapper.selectList(wrapper);
        List<GroupQueryRespDTO> collect = groupDOList.stream().map(each -> {
            GroupQueryRespDTO groupQueryRespDTO = BeanCopyUtils.copyBean(each, GroupQueryRespDTO.class);
            return groupQueryRespDTO;
        }).collect(Collectors.toList());
        return collect;
    }


}
